const router = require("koa-router")();
const Role = require("../models/rolesSchema");
const utils = require("../utils/utils");
router.prefix("/role");

// 查询角色(增)
router.get("/list", async (ctx, next) => {
  const { roleName } = ctx.request.query;
  const { page, skipIndex } = utils.pager(ctx.request.query);
  let params = {};
  if (roleName) params.roleName = roleName;
  try {
    let res = Role.find(params);
    let [list, total] = await Promise.all([
      res.skip(skipIndex).limit(page.pageNum),
      Role.countDocuments(params),
    ]);
    ctx.body = utils.success({ data: { list, total } });
  } catch (error) {
    ctx.body = utils.fail(error.stack);
  }
});

// 添加新角色权限
router.post("/add", async (ctx, next) => {
  const { roleName, remark } = ctx.request.body;
  if (!roleName) {
    ctx.body = utils.fail({ data: null, msg: "请填写角色名称", code: 400 });
  } else {
    // 查询有没有重复信息
    let res = await Role.findOne({ $or: [{ roleName }] }, "_id roleName");
    if (res) {
      ctx.body = utils.fail({
        data: null,
        msg: `检测到有重复角色,请勿重复添加`,
        code: 400,
      });
    } else {
      let role = new Role({
        roleName,
        remark,
      });
      role.save();
      ctx.body = utils.success({ data: null, msg: "角色添加成功", code: 200 });
    }
  }
});

// 改
router.post("/edit", async (ctx, next) => {
  const { _id, ...params } = ctx.request.body;
  params.updateTime = new Date();
  if (!_id) {
    ctx.body = utils.fail({ data: null, msg: "参数错误", code: 400 });
  }
  let res = await Role.findOneAndUpdate({ _id }, { ...params });
  ctx.body = utils.success({ data: null, msg: "角色编辑成功", code: 200 });
});

// 删
router.post("/delete", async (ctx, next) => {
  const { _id } = ctx.request.body;
  if (!_id) {
    ctx.body = utils.fail({ data: null, msg: "参数错误", code: 400 });
  }
  let res = await Role.findByIdAndRemove(_id);
  ctx.body = utils.success({ data: null, msg: "删除成功", code: 200 });
});

// 更改权限
router.post("/permission", async (ctx, next) => {
  const { _id, ...params } = ctx.request.body;
  let res = await Role.findOneAndUpdate({ _id }, { ...params });
  ctx.body = utils.success({ data: null, msg: "权限修改成功", code: 200 });
});
module.exports = router;
